package com.keli.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ConfigManager {
	public static final String FILE_NAME = "config";
	public static final String START_TIME = "starttime";
	private static Map<String, String> config = new HashMap<String, String>();
	
	static {
		loadFile();
	}
	
	/**
	 * 加载配置文件的键值对
	 */
	private static void loadFile() {
		File file = new File(FILE_NAME);
		if (!file.exists()) {
			return;
		}
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String line = null;
			// 一次读入一行，直到读入null为文件结束
			while ((line = reader.readLine()) != null) {
				int index = line.indexOf('=');
				// 没有容错处理
				String key = line.substring(0, index);
				String value = line.substring(index + 1);
				if (value.trim().isEmpty()) {
					value = null;
				}
				config.put(key.toLowerCase(), value);
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取最新分析时间，适用于程序的启动
	 * @return
	 */
	public static String loadStartTime() {		
		return config.get(START_TIME);
	}
	
	/**
	 * 保存最新的分析时间
	 * @param newStartTime
	 */
	public static void updateStartTime(String newStartTime) {
		try {
			FileWriter fw = new FileWriter(FILE_NAME);
			fw.write(START_TIME);
			fw.write('=');
			fw.write(newStartTime);
			fw.flush();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
